package com.quectel.cms.controller.entranceguard;


import com.quectel.cms.constants.CmsRedisCacheConstants;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.device.DeviceCategoryCodeConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.global.annotation.RequireTenants;
import com.quectel.constant.sys.SysConstants;
import com.quectel.core.module.device.service.DeviceCategoryService;
import com.quectel.core.module.entranceguard.dto.EntranceGuardAbilityConfigDto;
import com.quectel.core.module.entranceguard.service.EntranceGuardAbilityConfigService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-15 14:29:44
 */
@RestController
@RequestMapping("entranceGuardAbilityConfig")
@Tag(name = "EntranceGuardAbilityConfigController", description = "门禁能力配置相关api")
public class EntranceGuardAbilityConfigController extends BaseController {

    @DubboReference
    private EntranceGuardAbilityConfigService entranceGuardAbilityConfigService;
    @DubboReference
    private DeviceCategoryService deviceCategoryService;

    private static final String ENTRANCE_GUARD_ABILITY_EDIT_LOCK = CmsRedisCacheConstants.PROJECT_NAME + "ENTRANCE_GUARD_ABILITY_EDIT_LOCK:";

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "entranceGuardAbilityConfig:list")
    @Operation(summary = "门禁能力配置的分页查询列表")
    public Response<Page<EntranceGuardAbilityConfigDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        request.put("deviceCategoryId", String.valueOf(deviceCategoryService.selectCacheByCode(DeviceCategoryCodeConstants.INTELLIGENT_ENTRANCE_GUARD).getId()));

        int total = entranceGuardAbilityConfigService.queryTotal(request.getParams());

        List<EntranceGuardAbilityConfigDto> list = null;
        if (total > 0) {
            list = entranceGuardAbilityConfigService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<EntranceGuardAbilityConfigDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<EntranceGuardAbilityConfigDto>>ok().wrap(page);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "entranceGuardAbilityConfig:info")
    @Operation(summary = "查询单条门禁能力配置记录")
    public Response<EntranceGuardAbilityConfigDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (entranceGuardAbilityConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        EntranceGuardAbilityConfigDto entranceGuardAbilityConfigDto = entranceGuardAbilityConfigService.selectById(id);

        return Response.<EntranceGuardAbilityConfigDto>ok().wrap(entranceGuardAbilityConfigDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "entranceGuardAbilityConfig:edit")
    @Operation(summary = "保存单条门禁能力配置记录")
    @RequireTenants(values = SysConstants.SYS_TOP_TENANT_CODE)
    public Response<Object> save(@RequestBody @Validated EntranceGuardAbilityConfigDto entranceGuardAbilityConfigDto) {

        //填充基础数据
        fillSaveCommonData(entranceGuardAbilityConfigDto);

        entranceGuardAbilityConfigService.save(entranceGuardAbilityConfigDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("saveOrUpdate")
    @RequirePermissions(values = "entranceGuardAbilityConfig:edit")
    @RequireTenants(values = SysConstants.SYS_TOP_TENANT_CODE)
    @Operation(summary = "保存或者修改门禁能力配置")
    @Log(express = "门禁能力修改")
    public Response<Object> saveOrupdate(@RequestBody @Validated EntranceGuardAbilityConfigDto entranceGuardAbilityConfigDto) {
        Lock spinLock = RedisUtils.getSpinLock(ENTRANCE_GUARD_ABILITY_EDIT_LOCK + entranceGuardAbilityConfigDto.getDeviceTypeId());
        spinLock.lock();
        try {
            EntranceGuardAbilityConfigDto dbValue = entranceGuardAbilityConfigService.selectCacheById(entranceGuardAbilityConfigDto.getDeviceTypeId());
            if (dbValue != null) {
                entranceGuardAbilityConfigDto.setId(dbValue.getId());
                //填充基础数据
                fillEditCommonData(entranceGuardAbilityConfigDto);
                entranceGuardAbilityConfigService.updateById(entranceGuardAbilityConfigDto);
            } else {
                //填充基础数据
                fillSaveCommonData(entranceGuardAbilityConfigDto);
                entranceGuardAbilityConfigService.save(entranceGuardAbilityConfigDto);
            }

        } catch (Exception e) {
            logger.error("门禁能力编辑出错", e);
        } finally {
            spinLock.unlock();
        }


        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "entranceGuardAbilityConfig:edit")
    @Operation(summary = "修改单条门禁能力配置记录")
    @RequireTenants(values = SysConstants.SYS_TOP_TENANT_CODE)
    public Response<Object> update(@RequestBody @Validated EntranceGuardAbilityConfigDto entranceGuardAbilityConfigDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(entranceGuardAbilityConfigDto.getId()));
        if (entranceGuardAbilityConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(entranceGuardAbilityConfigDto);

        entranceGuardAbilityConfigService.updateById(entranceGuardAbilityConfigDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "entranceGuardAbilityConfig:delete")
    @Operation(summary = "批量删除存在的门禁能力配置记录")
    @RequireTenants(values = SysConstants.SYS_TOP_TENANT_CODE)
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (entranceGuardAbilityConfigService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        entranceGuardAbilityConfigService.deleteBatch(ids);

        return Response.ok();
    }
}
